<template>
  <div class="category-container">
    <el-card class="filter-container">
      <el-button type="primary" @click="handleAdd">添加分类</el-button>
    </el-card>

    <el-card>
      <el-table
        v-loading="listLoading"
        :data="list"
        row-key="id"
        border
        default-expand-all
        :tree-props="{children: 'children'}"
      >
        <el-table-column
          prop="class_name"
          label="分类名称"
          width="180"
        />
        <el-table-column
          prop="class_id"
          label="分类ID"
          width="100"
        />
        <el-table-column
          prop="goods_count"
          label="商品数量"
          width="80"
        />
        <el-table-column
          prop="icon"
          label="图标"
          width="250"
        />
        <el-table-column
          prop="modified"
          label="更新时间"
          width="180"
        />
        <!-- <el-table-column
          prop="level"
          label="层级"
          width="100"
        >
          <template slot-scope="{row}">
            <el-tag :type="row.level === 0 ? '' : 'success'">
              {{ row.level === 0 ? '一级' : '二级' }}
            </el-tag>
          </template>
        </el-table-column> -->
    
        <el-table-column
          label="操作"
          width="200"
        >
          <template slot-scope="{row}">
            <el-button
              type="text"
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="row.level === 0"
              type="text"
              size="small"
              @click="handleAddSub(row)"
            >
              添加子分类
            </el-button>
            <el-button
              type="text"
              size="small"
              class="delete-btn"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form
        ref="dataForm"
        :model="temp"
        :rules="rules"
        label-position="left"
        label-width="100px"
      >
        <el-form-item v-if="isSubCategory" label="父级分类">
          <el-input v-model="parentName" disabled />
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="temp.class_name" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="temp.sort" :min="0" :max="999" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCategoryList, createCategory, updateCategory, deleteCategory } from '@/api/categories'

export default {
  name: 'GoodsCategory',
  data() {
    return {
      list: null,
      listLoading: true,
      dialogVisible: false,
      isSubCategory: false,
      parentId: null,
      parentName: '',
      dialogTitle: '',
      params:{
        page:1,
        page_size:20,
        include_goods_count:true
      },
      temp: {
        id: undefined,
        class_name: '',
        parent_id: 0,
        level: 0,
        sort: 0
      },
      rules: {
        name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序值', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      this.listLoading = true
      try {
        const response = await getCategoryList(this.params)
        this.list = response.data.data.list
      } catch (error) {
        console.error('获取分类列表失败:', error)
        this.$message.error('获取分类列表失败')
      }
      this.listLoading = false
    },
    handleAdd() {
      this.dialogTitle = '添加分类'
      this.isSubCategory = false
      this.temp = {
        id: undefined,
        class_name: '',
        parent_id: 0,
        level: 0,
        sort: 0
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleAddSub(row) {
      this.dialogTitle = '添加子分类'
      this.isSubCategory = true
      this.parentId = row.class_id
      this.parentName = row.class_name
      this.temp = {
        id: undefined,
        class_name: '',
        parent_id: row.class_id,
        level: 1,
        sort: 0
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleEdit(row) {
      this.dialogTitle = '编辑分类'
      this.isSubCategory = row.level === 1
      if (this.isSubCategory) {
        const parent = this.list.find(item => item.class_id === row.parent_id)
        this.parentName = parent ? parent.class_name : ''
      }
      this.temp = Object.assign({}, row)
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该分类吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await deleteCategory(row.class_id)
        this.$message.success('删除成功!')
        this.getList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除分类失败:', error)
          this.$message.error('删除分类失败')
        }
      }
    },
    async submitForm() {
      try {
        await this.$refs['dataForm'].validate()
        const isNew = this.temp.id === undefined
        
        if (isNew) {
          await createCategory(this.temp)
        } else {
          await updateCategory(this.temp)
        }
        
        this.dialogVisible = false
        this.$message.success(`${isNew ? '添加' : '更新'}成功!`)
        this.getList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('提交表单失败:', error)
          this.$message.error('提交失败')
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.category-container {
  padding: 20px;
  
  .filter-container {
    margin-bottom: 20px;
  }
  
  .delete-btn {
    color: #F56C6C;
  }
}
</style> 